package cn.anl.service;





import cn.anl.mapper.SysPermissionMapper;
import cn.anl.mapper.SysRoleMapper;
import cn.anl.mapper.SysUserMapper;

import cn.anl.pojo.SysPermission;
import cn.anl.pojo.SysRole;
import cn.anl.pojo.SysUser;


import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Desc 自定义用户接口实现UserDetailsService
 * @Author 安奈
 * @Date 2024/6/25 12:00
 **/
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    /**
     * @Author 安奈
     * @Desc 用户表
     */
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * @Author 安奈
     * @Desc 角色表
     */
    @Resource
    private SysRoleMapper sysRoleMapper;

    /**
     * @Author 安奈
     * @Desc 权限表
     */
    @Resource
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetailsWrap userDetails = null;
        try{
            //根据username查询用户信息
            List<SysUser> userList = sysUserMapper.selectByUserNameSysUsers(username);
            if (CollectionUtils.isEmpty(userList)) {
                throw new UsernameNotFoundException("用户不存在");
            }
            SysUser sysUser = userList.get(0);
            //根据userId查询用户的配置的所有角色
            List<SysRole> sysRoleList = sysRoleMapper.findRolesByUserId(sysUser.getUserId());
            List<Long> roleIds = new ArrayList<>();
            if (!CollectionUtils.isEmpty(sysRoleList)){
                roleIds = sysRoleList.stream().map(SysRole::getRoleId).collect(Collectors.toList());
            }
            //根据roleId集合查询所有权限
            List<SysPermission> sysPermissionList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(roleIds)){
                sysPermissionList =sysPermissionMapper.findAllByRoleIds(roleIds);
            }

            Set<GrantedAuthority> authorities = new HashSet<>();
            if (!CollectionUtils.isEmpty(sysPermissionList)){
                sysPermissionList.forEach(data-> authorities.add(new SimpleGrantedAuthority(data.getPermissionCode())));
            }
            userDetails = new UserDetailsWrap(sysUser,new ArrayList<>(authorities));
        }catch (Exception e){
            e.printStackTrace();
        }
        return userDetails;
    }

}